package com.db.server;

import java.util.HashMap;
import java.util.Map;

import com.db.server.data.OrderBook;
import com.db.server.data.ServerOrder;

public class Exchange {
	
	Map<String, OrderBook> orders;
	
	public Exchange() {
		orders = new HashMap<String, OrderBook>();		
	}

	public void addOrderBook(String ticketSymbol) {
		if (!orders.containsKey(ticketSymbol)) {
			synchronized(orders) {
				orders.put(ticketSymbol, new OrderBook(ticketSymbol));
			}
		}
	}
	
	public boolean hasTicketSymbol(String ticketSymbol) {
		return orders.containsKey(ticketSymbol);
	}
	
	public boolean hasOrder(String orderID) {
		for (OrderBook orderBook : orders.values()) {
			if (orderBook.hasOrder(orderID)) {
				return true;
			}
		}
		return false;
	}
	
	public ServerOrder getOrder(String orderID) {
		for (OrderBook orderBook : orders.values()) {
			ServerOrder order = orderBook.getOrder(orderID);
			if (order != null)
				return order;
		}
		return null;
	}

	public void add(ServerOrder order) {
		orders.get(order.getTicketSymbol()).add(order);
	}
	
	public void remove(ServerOrder order) {
		orders.get(order.getTicketSymbol()).remove(order);
	}
	
	
	public ServerOrder bestBuyOrder(String ticketSymbol) {
		return orders.get(ticketSymbol).bestBuyOrder();
	}

	public ServerOrder fisrtBuyMarketOrder(String ticketSymbol) {
		return orders.get(ticketSymbol).firstBuyMarketOrder();
	}
	
	public ServerOrder bestSellOrder(String ticketSymbol) {
		return orders.get(ticketSymbol).bestSellOrder();
	}

	public ServerOrder fisrtSellMarketOrder(String ticketSymbol) {
		return orders.get(ticketSymbol).firstSellMarketOrder();
	}
	
	
	public boolean hasBuyOrder(String ticketSymbol) {
		return orders.get(ticketSymbol).hasBuyOrder();
	}

	public boolean hasBuyMarketOrder(String ticketSymbol) {
		return orders.get(ticketSymbol).hasBuyMarketOrder();
	}
	
	public boolean hasSellOrder(String ticketSymbol) {
		return orders.get(ticketSymbol).hasSellOrder();
	}

	public boolean hasSellMarketOrder(String ticketSymbol) {
		return orders.get(ticketSymbol).hasSellMarketOrder();
	}
}
